final spine = 0.346" Responsive Responsive Design Responsive

withWordPress Design With the ever-increasing need to view on mobile devices, websites have to be adaptable to thousands of different screen resolutions. In Responsive Design with WordPress, expert web

developer Joe Casabona teaches you how to leverage WordPress with to get the most out of responsive design, implement best practices,

automate important processes, and make your life easier overall. WordPress Design You’ll start with a refresher on the core functionality of WordPress, then dive into developing responsive themes and plugins. Find out what to consider at the outset of the design process to save hours of work during redesigns. Learn up-to-date best practices for deter- with mining breakpoints, accessibility, and preventing bloat for better user experience no matter the user’s connection speed. Finally, you’ll apply the principles you learn to specific tutorials, WordPress such as building a photo gallery, map page, and products page. How to make great responsive • Learn when to rely on themes and when it’s best to use plugins. Joe Casabona is a , teacher, speaker, and • Apply your responsive CSS to a WordPress theme. writer currently working for the themes and plugins • Learn various navigation techniques, such as Jump to with University of Scranton. He has smooth scrolling or Select box. been making websites since 2002 and using WordPress • Use popular responsive techniques, like picturefill.js, to make since 2004. He is also the author images respond to different screen resolutions and connection of Building WordPress Themes speeds. from Scratch. • Explore frameworks, including Bootstrap and Foundation. • Download dozens of code samples to help implement responsive design techniques, and test yourself with end-of-chapter quizzes. SAB C a on a

US $39.99 Can $41.99

Level: Intermediate Category: Web Development/ www.newriders.com Cover Design: Aren Straiger Joe Casabona

9780321957412_ResponsiveWordPress_Cvr.indd 1 11/13/13 10:56 AM Responsive DESIGN with WordPress

How to make great responsive themes and plugins

Joe Casabona Responsive Design with WordPress Joe Casabona New Riders www.newriders.com To report errors, please send a note to: [email protected] New Riders is an imprint of Peachpit, a division of Pearson Education. Copyright © 2014 by Joseph Casabona Acquisitions Editor: Michael Nolan Project Editor: Nancy Peterson Development Editor: Eric Schumacher-Rasmussen Copyeditor: Joanne Gosnell Proofreader: Scout Festa Technical Reviewer: Stephen N. Mekosh Production Coordinator: David Van Ness Compositor: Danielle Foster Cover Designer: Aren Straiger Interior Designer: Danielle Foster Indexer: FireCrystal Communications Notice of Rights All rights reserved. No part of this book may be reproduced or transmitted in any by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting permission for reprints and excerpts, contact [email protected]. Image of Treo used courtesy Jonathan Vasata/Shutterstock. Notice of Liability The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of the book, neither the author nor Peachpit shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the computer software and hardware products described in it. Trademarks WordPress is a registered trademark of the WordPress Foundation in the United States and/or other countries. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Peachpit was aware of a trademark claim, the designations appear as requested by the owner of the trademark. All other product names and services identified throughout this book are used in editorial fashion only and for the benefit of such companies with no intention of infringe- ment of the trademark. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with this book. ISBN 13: 978-0-321-95741-2 ISBN 10: 0-321-95741-5 9 8 7 6 5 4 3 2 1 Printed and bound in the United States of America Dedication

To my parents, Louis and Marie, for their continued support. And to Joe and Jean Rizzi, whose advice, kindness, and patience helped me get to where I am today. iv RESPONSIVE DESIGN WITH WORDPRESS

Acknowledgments

I’ like to thank the following people, without whom this book wouldn’t be in your hands:

RR Stephen Mekosh for not only being a fantastic tech editor and a good friend, but also being the first person to show me both CSS and WordPress.

RR Michael Nolan for giving me the chance to write this book and welcoming me to Peachpit Press/New Riders.

RR Nancy Peterson and Eric Schumacher-Rasmussen for advice and guidance, editing, keeping me on track, and our weekly talks.

RR Joanne Gosnell and Scout Festa for copyediting and proofreading, respec- tively, and for making it seem like I have a good command over grammar and the English language.

RR The design team at Peachpit Press for making this book look amazing.

RR Jesse Friedman for the wonderful foreword and kind words.

RR Jason Coleman, Stephanie Leary, Lisa Sabin-Wilson, and Pippin Williamson for letting me pick their brains on both WordPress and the art of writing a book.

RR My family and friends, especially my parents; my brothers Phil, Mike, and Rob; Dave Redding; Rob McManus; Matt Wren; and my wonderful girlfriend, Erin Holman.

I’d also like to make a quick mention of my brother Phil’s website, http://phil.casabona.org. He took the headshot used in this book, and I love his work. Contents v

Contents

Foreword viii Introduction x Chapter 1 What Is Responsive Web Design? 1 Responsive Web Design Origins 2 Breakpoints & Media Queries 3 The Current State of Devices 7 Consider Connection Speeds 8 Wrapping Up 11 Chapter 2 Creating a Basic WordPress Theme 13 Meet Our Website 16 Template Structure 16 The Loop 23 Custom Post Types 26 Plugins and Shortcodes 29 Wrapping Up 33 Chapter 3 Making Your Theme Responsive: The Ground Floor 35 Responsive Techniques 36 Adding the Responsive Layout 42 Testing WordPress’ Default CSS Classes 47 Wrapping Up 55 vi RESPONSIVE DESIGN WITH WORDPRESS

Chapter 4 Making Your Theme Responsive: Core Features 57 Handling Navigation 58 Handling Images 75 Handling Widgets 81 Wrapping Up 88 Chapter 5 Making Your Theme Responsive: Features 91 Handling Comments 92 Handling Archives 103 Wrapping Up 119 Chapter 6 Using Responsive Theme Frameworks 121 Some Principles of Reuse to Keep in Mind 122 About WordPress Frameworks 129 Popular WordPress Frameworks 132 Wrapping Up 140 Chapter 7 Techniques and Tutorials 141 Introduction 142 How to Build a Responsive WordPress Photo Gallery 144 How to Build a Responsive WordPress Map Page Using Google Maps 150 How to Build a Responsive WordPress Image Slider 154 Contents vii

How to Build a Responsive WordPress Contact Form 161 How to Build a Responsive WordPress Products Page 167 Wrapping Up 177 Appendix Resources 179 A Few Words to Sum Up 180 Books 181 Meetups 184 Links 185 Index 186 viii RESPONSIVE DESIGN WITH WORDPRESS

Foreword

By Jesse Friedman Today WordPress powers 20% of all websites, and we can look forward to it powering 1 in 4 sites launched in 2014. I launched my first WordPress-powered website in 2005, before all the “cool kids” were doing it. I am very proud to be a veteran developer and strategist for a product used by millions of people all over the world.

Since I launched that first site back in 2005, I have written my own book on devel- oping for WordPress, and I have a few more coming out in spring 2014. I have also contributed to other books and written articles for online publications such as Smashing Magazine and net Magazine, and I teach both in universities and online. I have also spoken at conferences all over the world, including one where I met Joe Casabona.

I was honored when Joe asked me to write the foreword for this book, because I knew it was going to be great. Joe has a real talent for turning complicated solu- tions into very simple step-by-step directions. WordPress was built to be simple— simple to set up, simple to install, and simple to extend. Still, it can be somewhat challenging to understand for novice designers and developers who are looking to build on basic WordPress functionality.

These challenges prompted me to write my book Web Designer’s Guide to WordPress: Plan, Theme, Build, Launch in 2012 and is exactly why Joe wrote his book this year. We are both veteran developers who want to help grow the WordPress community. The best way to do that is to help educate the community and share our experiences and knowledge around a product we use every day. Joe has done just that with Responsive Design with WordPress. This is a solid book with lots of great examples.

As a professor at two universities in Rhode Island, I know this book will compli- ment my class curriculum beautifully. The lessons, examples, and even questions at the end of each chapter help you build a great foundation on WordPress and Responsive Web Design. You also will develop a WordPress theme as you follow along with the book, so you’ll be reinforcing the skills you’re building as you read. Foreword ix

Not to mention you’ll be learning two skills at the same time. You’ll be learning WordPress and, at the same time, gaining experience specifically in Responsive Web Design. This approach will not only help to strengthen your skills in both areas but will also make you an expert in a very profitable niche.

As I mentioned earlier, WordPress will power 25% of all websites launched in 2014. This means that 1 in 4 new sites will need a developer who knows WordPress. What’s more, as of this year more information is being consumed on mobile devices than on traditional computers. If you didn’t have strong skills in Responsive Web Design in 2013, you’re definitely going to need them in 2014 and beyond.

In my opinion, there is no better way to learn a skill than by doing it yourself. This book is the best way to learn both WordPress and Responsive Web Design at the same time. Great job, Joe! x RESPONSIVE DESIGN WITH WORDPRESS

Introduction

I got my first portable device when I was a freshman in high school. It was the Palm m100 and I loved it dearly. It didn’t do much, and, well, at 13 or 14 I didn’t have much to use it for. But having a computer in my pocket? Crazy! As a result, it went everywhere with me (and may have gotten taken away once or twice after I used it in class).

Then I moved to the Compaq iPAQ, which ran Windows and had a color screen. Even crazier, I thought. I could run real programs on this. I even asked about campus Wi-Fi when I was visiting colleges in the early 2000s, when it was just becoming popular. I thought of all the amazing things I could do with a tiny com- puter that came with a pen (stylus) and fit in my pocket. Still, I found myself want- ing more after a while. This brings me to my first smartphone: the Palm Treo 650 (Figure 0.1).

Figure 0.1 Oh, Treo 650. I still miss you sometimes. Introduction xi

I would do everything on this phone—make calls, take photos, sync my Google Account to it. It even had a primitive browser called Blazer. I could visit websites from my phone!

Since then, of course, the mobile landscape has changed. The iPhone brought a full-featured browser to mobile devices, capable of everything from CSS to JavaScript. It didn’t solve one problem, though: the problem of the small screen. That’s where Responsive Web Design comes in.

Perhaps you’ve heard of it. It’s apparently pretty popular right now. Lots of people—developers, designers, agencies, and users—are asking about it. And why shouldn’t they? On top of catering to what is a quickly growing market, it’s pretty cool. Responsive Web Design has become one of those things people check for when they visit a site (resizing a webpage is totally the new “check the source for table layouts”).

If you’re designing a website, you ultimately have no control over how it’s viewed; you don’t get to decide where it’s viewed or what it’s viewed on or the connection on which it’s viewed. That might sound scary to some, but to me (and I bet to you, too) it’s quite the contrary. I love solving that problem. That’s not to say it’s not a little daunting. I mean, you need to create a website that is easy to use on mobile but that totally “wows” on the desktop. That’s what Responsive Web Design is all about.

WordPress is pretty great too. It powers millions of webpages. Hundreds of mil- lions, even. As you read in the Foreword, it will run 1 of every 4 websites launched in 2014. It does a lot for us while allowing us to do a lot. So how does WordPress fit in with Responsive Web Design? Well, as it turns out, it can be really helpful when creating responsive themes; it has a lot of really great built-in features that we, as developers, can leverage to create better responsive sites. And that’s just what I’m going to show you how to do.

Who Is This Book for? I’d like to tell you that this book is for anyone looking to develop WordPress sites, but in order to get into the real heart of why I wrote this book, I need to make a few assumptions about you, dear reader.

First, I assume you have a working knowledge of HTML, CSS, PHP, JavaScript, and MySQL. I also assume you have some familiarity with WordPress—you’ve installed it, you use it, you’ve possibly even coded a theme for it. Finally, I assume you’ve used a server in some capacity; you should at least know the WordPress directory structure and how to use FTP/SFTP. xii RESPONSIVE DESIGN WITH WORDPRESS

So this book is for web developers and WordPress developers who want to take advantage of what WordPress has to offer in order to create great responsive websites. In this book, we are going to cover a wide range of topics and techniques for converting website elements to responsive WordPress theme features.

I will provide a bit of a primer, however. In the first chapter, we will take a closer look at Responsive Web Design: what it is, where it came from, and best practices for using it. Then, there will be a brief overview of WordPress theme develop- ment; this will go over some of the major parts of the WordPress theme—impor- tant files, the Loop, Custom Post Types, plugins, and more. Then, we’ll get into the real fun part.

The real meat of the book—making a responsive WordPress theme—is divided into three parts. Chapter 3 will cover prominent responsive techniques and how to integrate them into the WordPress theme. Chapters 4 and 5 will look at specific components of a WordPress website, including navigation, images, com- ments, widgets, archives, and plugins.

We will wrap up the book by looking at responsive theme frameworks and child themes in Chapter 6, followed by a cookbook-style section full of tutorials for responsive development in Chapter 7.

Why Did I Write This Book? When I came up with the idea for this book, there were a lot of things floating through my head. Responsive Web Design is always changing; WordPress is always changing. The best practices of a couple of years ago have changed in both fields, and it’s important to get that information out.

There is a big movement in the web development community toward “doing responsive responsibly” (a phrase coined by Scott Jehl); this is the idea that responsive isn’t just about screen sizes. There is another big movement in the WordPress community to remove functionality from themes (features such as sliders and Custom Post Types that rely on content). I wanted to create a single place that talks about these things, as a lot of web developers are likely working with both responsive design and WordPress. Introduction xiii

Coding Conventions First of all, any code you come across in the book will be presented in one of two ways. It could be inline, like this: , or it could be in its own block, which looks like this:

function hello_world(){ $s= “Hello World”; return $s; } print hello_world();

Either way, you should be able to recognize it pretty quickly. As far as standards, the WordPress Codex lays out quite a few (http://rwdwp.com/16). I will do my best to adhere to these coding standards.

To denote that the code on the page takes place in the middle of a block of code (that is, there was some code skipped between the first line listed and the next), look for an ellipses (...). A couple of things I’d like to point out: I will be using HTML5 markup here, but we won’t do anything with the more advanced facets of HTML5, like Web Sockets or Storage APIs.

In most cases, the CSS will use .classes instead of #ids. This should make for cleaner CSS while eliminating the need for really specific selectors. All of my CSS will be formatted like this:

.class-name{ color: #FFFFFF; background: #000000; }

Notice the use of dashes (-) instead of camel case or underscores, and the fact TIP that the closing bracket is also indented. This makes it easier to read the CSS, Look for text like especially when there is a lot. this in the margins for Tips and Notes. Conversely, my PHP function names will always use underscores (_) and be pre- fixed with mf_, like this:mf_get_featured_images() . xiv RESPONSIVE DESIGN WITH WORDPRESS

Finally, sometimes the layout limitations of a print publication mean that we have to stretch single lines of code over more than one line. In those cases, you’ll see a light gray arrow (p) to indicate that these lines of code should not be broken when you use them. If you’ve got the digital version of this book, you may find that code breaks unpredictably in the text. In that case, it’s important to rely on the downloadable files (www.rwdwp.com) for accuracy.

Other Book Notes There is a lot of code in the book. Most of the time I will point out where you can find that code. If I don’t, all of it is available on the book’s website, www.rwdwp.com, as well as on GitHub. You will also find a list of all the short URLs and the sites they point to.

As you code throughout the book, you’ll notice that I don’t make much mention of testing before Chapter 6; it’s important to test on at least a couple of devices, especially if you plan on using these techniques in production-ready sites (and I hope you do).

Finally, I tend to use a lot of acronyms, which are usually defined in context. In case they aren’t, here are the most common ones:

RR RWD: Responsive Web Design

RR WP: WordPress

RR RESS: Responsive Design + Server Side Components

RR The Codex: the WordPress Codex (or documentation of the API) Chapter4 Making Your Theme Responsive: Core Features 58 RESPONSIVE DESIGN WITH WORDPRESS

So far, you’ve seen multiple ways to make a website responsive. Now it’s time to really dig in and combine those techniques with WordPress’ unique capabilities.

In Chapter 3, you learned how to apply your responsive CSS to a WordPress theme. You also got an in-depth look at WordPress’ generated CSS classes and created some default styles for what are considered the “essential” ones. From here on out, you’ll go even further, focusing on two types of features: core and blog.

This chapter looks at some of the core features of WordPress instrumental to a good User Experience. The next chapters are about using what WordPress provides developers and leveraging those tools to create better responsive sites. That said, you’ll look at three areas of development in this chapter: navigation menus, images, and widgets. Handling Navigation Responsive navigation techniques are bountiful in books and blog posts; many developers have come up with their own implementations for navigation menus on responsive sites. Brad Frost outlines some of the most popular ones at http://rwdwp.com/32.

In this section, we will look at a few popular techniques and how they look on the Millennium Flights site, and then decide what’s best.

A Look at Popular Techniques If you looked at Brad Frost’s post, you’ll see that he also wrote a second one and linked to several others. In other words, there are lots of navigation menu pat- terns to choose from.

We will explore three possible options for the Millennium Flights navigation: Do Nothing (or Top Nav), Jump to (or Footer nav), and the Select box…plus a bonus technique that may surprise you. While we won’t be implementing it, we will also look at the Off-Canvas technique, which is a bit more advanced

DO NOTHING (OR TOP NAV) This is the easiest one to implement. You simply leave the navigation as is at the top of your site; you’ll see what the “technique” looks like in Figure 4.1. Making Your Theme Responsive: Core Features 59

“Hide and Cry”

Frost mentions one technique in which you hide your navigation from mobile users, naming it “Hide and Cry.” This reflects the all-too-prevalent thinking that users on mobile don’t need as much function- ality as those on the desktop, and it’s wrong. 31% of American adults in 2012 used their phones for the majority of their access. In essence, you’re punishing mobile users by limiting their experience and making them download content that they’ll never see. It might be a convenient way to handle other pages—saving on page height and adjusting the navigation—but it’s a bad practice, for some of the reasons discussed in Chapter 1, primarily that you make users download sections of websites they will never see, increasing bandwidth required to download the site and slowing things down.

Figure 4.1 Millennium Flights with the “Do Nothing” responsive navigation technique.

As long as your navigation styles are not limited by a specific Media Query, they will apply to the entire site if you employ the Do Nothing technique. It is easy to apply because you don’t have to make changes to your code, but there are some pitfalls. Luckily the navigation for Millennium Flights uses big text, but imagine a site with smaller text using this approach. Users may have difficulty selecting the menu items on smaller screens (Figure 4.2).

Figure 4.2 On the left is how this website navigation renders on an Android phone. On the right, you see what happens when you resize the browser. In both cases, the nav appears small and difficult to press without zooming. 60 RESPONSIVE DESIGN WITH WORDPRESS

The other big issue with the technique is that as a user adds more menu items, the height of the page increases. You don’t want to have a situation where the user only sees a logo and menu items on page load on a smart phone.

“DO SOME THINGS” I have a slight modification to this approach, which I’ve very cleverly called “Do Some Things.” It’s the idea that functionally, nothing about the navigation changes; it doesn’t change locations or implementations. It’s still an unordered list at the top of the page. That is, it will stay in the same place and it will be a list of menu items, exactly the same on both layouts. However, you do make slight tweaks and changes to the CSS, optimizing it a little bit for mobile. An example can be seen on my personal site, Casabona.org (Figure 4.3).

Figure 4.3 Casabona.org’s navigation on both mobile and desktop layouts. The position of the navigation doesn’t change, but the items become more button-like on mobile to make pressing them easier for the user.

NOTE Not too much has changed in the overall webpage layout, but you’ll see each menu It should be men- item on smaller screens is its own individual button (as opposed to the contiguous tioned that this grey bar on wider screens), and the font gets a little bolder on smaller screens. section isn’t going to present a single This slightly modified approach still runs into some of the pitfalls of the “Do “right” approach; it Nothing” approach, like taking up a lot of screen real estate on small screens. all depends on the situation. These are JUMP TO OR FOOTER ANCHOR just the options. In this technique, as the screen gets smaller, the navigation is replaced by a single link that jumps the user to navigation in the footer. This, like the “Do Nothing” approach, is easy to implement, but it saves on screen real estate, as the menu is no longer at the top to take up space (Figure 4.4). Making Your Theme Responsive: Core Features 61

Figure 4.4 The Jump to navigation. The menu items are replaced with a single link that brings users to the bottom of the page.

There are a couple of ways to code this technique. The most common one is to use CSS’s display: none; to hide the navigations that should not be in use. For example, if this is the header and footer markup:

Header Markup

Footer Markup

The CSS would look like this:

nav#main .full{ display: none; }

#footernav ul{ margin: 0; padding: 0; }

#footernav li{ font-size: 1.5em; 62 RESPONSIVE DESIGN WITH WORDPRESS

border-bottom: 1px solid #FFFFFF; }

#footernav li a{ padding: 10px; }

... @media screen and (min-width: 34.188em){

...

nav#main .full{ display: block; } #footernav, nav#main .jump{ display: none; }

... }

This code works fine, but it’s forcing the user to download code that he isn’t going to see. Later in this section, you are going to see how this method can be improved using RESS.

Aside from the extra code, this experience might be a jarring one for the user. The page view would change from the top of the page to the bottom without any scrolling or animations, changing everything the user was looking at; it’s not very smooth. A better solution, and one that takes into account the issues we’ve seen with the techniques we’ve looked at, would be to convert the navigation to a Select box for mobile.

THE SELECT BOX The Select box is a clean, user-friendly method that places the navigation at the top of the page without taking up too much screen space. One drawback is that it’s not as easy to implement as the previous methods because you actually need to code up two separate menus—one normal menu, and one inside of a select box (Figure 4.5). Making Your Theme Responsive: Core Features 63

Adding Smooth Scrolling to the “Jump to” Technique

You can make the transition a bit smoother using a jQuery scroll effect. After adding jQuery, add this function to your header (or functions.php using the wp_head action):

$(function() { $(‘a[href*=#]:not([href=#])’).click(function() { if (location.pathname.replace(/^\//,’’) == pthis.pathname.replace(/^\//,’’) || location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $(‘[name=’ + pthis.hash.slice(1) +’]’); if (target.length) { $(‘,body’).animate({ scrollTop: target.offset().top }, 1000); return false; } } }); });

Figure 4.5 The Select box navigation approach clears up a lot of room while still keeping navigation at the top; however, the user still has to download two different navigation menus. 64 RESPONSIVE DESIGN WITH WORDPRESS

Let’s think outside of WordPress for a second, and look at the HTML structure for a select menu navigation:

While this seems like a pretty standard implementation, it’s actually going to take a little bit of work to get this properly working in WordPress because it changes the entire structure of the menu. Luckily, WordPress allows developers to do just that with the Walker_Nav_Menu class. A “Walker” in programming is a way to tra- verse, or process, tree-like data structures, which create hierarchical data. In this case, it’s traversing HTML to create an unordered list of nav items. You will create a file called Select_Nav_Walker.php, where you will write a class that extends Walker_Nav_Menu, using the four functions it uses to display the menu:

class Select_Nav_Walker extends Walker_Nav_Menu {

public function start_lvl(&$output, $depth){} public function end_lvl(&$output, $depth){} public function start_el(&$output, $item, $depth, $args){} public function end_el(&$output, $item, $depth){} }

The functions start_lvl and end_lvl print the opening and closing elements for the menu; by default this is

    and
. You will actually add the new markup (the %3$s’, ‘container’ => false ) ); ?>